package online.exam.utils;

import java.security.MessageDigest;
import java.util.Objects;

/**
 * @author 小阳Sheep.
 * created on 2020/2/18 9:48
 */
public class MD5Tools {

    private static String byteArrayToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(byteToHexString(b));
        }
        return sb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n += 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    public static String md5Encode(String origin, String charsetName) {
        try {
            MessageDigest md = MessageDigest.getInstance("md5");
            if (charsetName == null || "".equals(charsetName))
                origin = byteArrayToHexString(md.digest(origin.getBytes()));
            else
                origin = byteArrayToHexString(md.digest(origin.getBytes(charsetName)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Objects.requireNonNull(origin).toUpperCase();
    }

    public static String md5EncodingUtf8(String origin) {
        return md5Encode(origin, "utf-8");
    }

    private static final String[] hexDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d",
            "e", "f"};

}
